﻿@using System.ComponentModel.DataAnnotations
@using Blazor.Localization
@using Blazor.Model.Dto
@using Blazor.Validators
@inherits Blazor.Core.SoraniFeedbackComponentBase<Empty, NewHotUpdateSettingResult?>
@inject IStringLocalizer<UpdateSettingLocalization> Loc

<Form @ref="_form" Model="_model" LabelColSpan="8" WrapperColSpan="16" LabelAlign="AntLabelAlignType.Left">
    <FormItem Label="@Loc[UpdateSettingLocalization.NativeVersion]">
        <Input @bind-value="@context.NativeVersion"/>
    </FormItem>

    <FormItem Label="@Loc[UpdateSettingLocalization.ResourceUrl]">
        <Input @bind-value="@context.ResourceUrl"/>
    </FormItem>

    <FormItem Label="@Loc[UpdateSettingLocalization.RawResourceVersion]">
        <Input @bind-value="@context.RawResourceVersion"/>
    </FormItem>

    <FormItem Label="@Loc[UpdateSettingLocalization.DefaultResourceVersion]">
        <Input @bind-value="@context.DefaultResourceVersion"/>
    </FormItem>

    <FormItem Label="@Loc[UpdateSettingLocalization.VersionComment]">
        <Input @bind-value="@context.Comment"/>
    </FormItem>
</Form>

@code {
    private class FormData
    {
        [Range(0, 999999, ErrorMessageResourceName = nameof(ValidatorLocalization.InvalidNativeVersion), ErrorMessageResourceType = typeof(ValidatorLocalization))]
        public uint NativeVersion { get; set; }

        public string ResourceUrl { get; set; } = string.Empty;

        [Required]
        public string RawResourceVersion { get; set; } = string.Empty;

        [Required]
        public string DefaultResourceVersion { get; set; } = string.Empty;

        public string Comment { get; set; } = string.Empty;
    }

    private FormData _model = new();
    private Form<FormData> _form;

    public override Task OnFeedbackOkAsync(ModalClosingEventArgs args)
    {
        if (!_form.Validate())
        {
            args.Reject();
            return Task.CompletedTask;
        }

        var result = new NewHotUpdateSettingResult()
        {
            NativeVersion = _model.NativeVersion,
            ResourceVersionEntry = new ResourceVersionEntry()
            {
                Raw = _model.RawResourceVersion,
                Default = _model.DefaultResourceVersion,
                Comment = _model.Comment,
            },
            ResourceUrl = new Uri(_model.ResourceUrl),
        };
        
        OkCancelRefWithResult.OkAsync(result);
        
        return Task.CompletedTask;
    }

}